<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of NetworkController
 *
 * @author mateusz.ledzewicz
 */
class Network_preparedController extends FormListController {
    protected function begin() {
        $this->view = new ViewNetwork_prepared();
        
    }

    protected function listRun(){
        $this->view->setSpecialVar('list', Network_prepared::getAll());
        $this->view->setModel(Network_prepared::loadModel(), 'header'); 
    }
    
    protected function formRun(){
        $id = (isSet($_GET['id']) && !empty($_GET['id'])) ? $_GET['id'] : null;
        $id_parent = (isSet($_GET['parent']) && !empty($_GET['parent'])) ? $_GET['parent'] : null;
        $parent = Network::loadModel($id_parent);
        if(is_null($parent) || $parent ->NewRecord)
        {
            throw new Exception('Bad parent id');
        }
        
        $model = Network_prepared::loadModel($id);
        
       if(count($_POST) > 0){
            $params = '';
            $model->setValues($_POST);
            if(is_null($model->name))
            {
                $model->name=$parent->name;
            }
          
            if($model->NewRecord && Network_prepared::loadSpecialModel("name = '{$model->name}' ")->NewRecord == FALSE)
            {
                throw new Exception('Network with this name exists');
            }
             
            $model->id_network = $parent;
            
            $model->information .= 'Parent file: '.$parent->file.' ';
            $model->information .= 'Training function:'.$_POST['training_function'].' ';
            $model->information .= 'Stop function:'.$_POST['stop_function'].' ';
            
            $params .= BasicFunctions::prepareFileName($parent->name).' ';
            $params .= $_POST['training_function'].' ';
            $params .= $_POST['stop_function'].' ';
            $params .= BasicFunctions::prepareFileName($model->name);
            copy($parent->file, basename($parent->file));
            
            exec(ConfigPath::network_prepare.' '.$params, $output);
            
            if($output[0] != '1')
            {
                throw new Exception('Create_network failed');
            }
            
            unlink(basename($parent->file));
            $model->file=$output[1];
            rename($model->file, ConfigPath::network_prepare_output_dir.$model->file);
            $model->file = ConfigPath::network_prepare_output_dir.$model->file;
            $model->save();
            
            header("Location: index.php?step=network_prepared");
       
       }
       $this->view->setModel($model, 'edit');
    }


        
        
        //put your code here
}

?>
